import streamlit as st
import os
import sys
import auth
import database as db
from ui import login, upload, detection, visualization

# 创建数据目录
os.makedirs("data", exist_ok=True)
os.makedirs("data/uploads", exist_ok=True)
os.makedirs("data/processed", exist_ok=True)
os.makedirs("data/static", exist_ok=True)

# 设置页面配置
st.set_page_config(
    page_title="行人轨迹跟踪与分析系统",
    page_icon="👣",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 添加自定义CSS以改进视频播放
st.markdown("""
<style>
    video {
        width: 100% !important;
        max-height: 500px !important;
    }
    .stVideo {
        width: 100% !important;
    }
</style>
""", unsafe_allow_html=True)

# 检查静态文件目录是否存在且可访问
static_dir = os.path.join(os.getcwd(), "data", "static")
if not os.path.exists(static_dir):
    os.makedirs(static_dir, exist_ok=True)
    print(f"创建静态资源目录: {static_dir}")

# 打印一些系统信息以便调试
print(f"当前工作目录: {os.getcwd()}")
print(f"静态资源目录: {static_dir}")
print(f"Streamlit版本: {st.__version__}")

# 初始化数据库
if not os.path.exists("data/pedestrian_tracking.db"):
    db.init_db()

# 初始化当前页面
if 'current_page' not in st.session_state:
    st.session_state.current_page = "login"

# 侧边栏导航
def render_sidebar():
    st.sidebar.title("导航")
    
    # 用户信息
    if st.session_state.logged_in:
        user_type = "管理员" if st.session_state.user['is_admin'] else "普通用户"
        st.sidebar.write(f"当前用户: **{st.session_state.user['username']}** ({user_type})")
        
        # 导航菜单
        if st.sidebar.button("文件上传"):
            st.session_state.current_page = "upload"
            st.rerun()
        
        if st.sidebar.button("视频处理"):
            if 'selected_video_id' in st.session_state:
                st.session_state.current_page = "detection"
                st.rerun()
            else:
                st.sidebar.warning("请先从上传页面选择视频")
        
        if st.sidebar.button("数据分析"):
            if 'selected_video_id' in st.session_state:
                st.session_state.current_page = "visualization"
                st.rerun()
            else:
                st.sidebar.warning("请先从上传页面选择视频")
        
        if st.session_state.user['is_admin']:
            if st.sidebar.button("用户管理"):
                st.session_state.current_page = "admin"
                st.rerun()
        
        if st.sidebar.button("登出"):
            auth.logout()
            st.session_state.current_page = "login"
            st.rerun()
    
    st.sidebar.markdown("---")
    st.sidebar.markdown("### 行人轨迹跟踪与分析系统")
    st.sidebar.markdown("基于YOLOv8和DeepSORT")
    st.sidebar.markdown("© 2025 版权所有")

def main():
    """主应用"""
    # 初始化认证状态
    auth.init_auth()
    
    # 渲染侧边栏
    if st.session_state.current_page != "login":
        render_sidebar()
    
    # 显示当前页面
    if st.session_state.current_page == "login":
        if login.render():
            st.session_state.current_page = "upload"
            st.rerun()
    
    elif st.session_state.current_page == "upload":
        upload.render()
    
    elif st.session_state.current_page == "detection":
        detection.render()
    
    elif st.session_state.current_page == "visualization":
        visualization.render()
    
    elif st.session_state.current_page == "admin":
        if st.session_state.user['is_admin']:
            auth.manage_users()
        else:
            st.error("需要管理员权限")
            st.session_state.current_page = "upload"
            st.rerun()

if __name__ == "__main__":
    main() 